package com.gws.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Hello world!
 *
 */

class Ticket{
	private int number = 30;
	Lock lock = new ReentrantLock(); //可重入锁(轻量级锁)
	
	public void sale(){
		lock.lock();
		try {
			if(number > 0){
				System.out.println(Thread.currentThread().getName()+"卖出第:"+(number--)+"还剩余："+number);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
}
/**
 * 多线程
 * @author gws
 *
 */
public class SaleTicket01 
{
    public static void main( String[] args )
    {
    	final Ticket ticket = new Ticket();
    	//使用Lamda
    	new Thread(() -> {for (int i = 1; i < 40; i++) ticket.sale();},"A").start();
    	new Thread(() -> {for (int i = 1; i < 40; i++) ticket.sale();},"B").start();
    	new Thread(() -> {for (int i = 1; i < 40; i++) ticket.sale();},"C").start();
    	// 使用runnable的方式
        /*new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i < 40; i++) {
					ticket.sale();
				}
			}
		}, "aa").start();
        
        new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i < 40; i++) {
					ticket.sale();
				}
			}
		}, "bb").start();
        
        new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i < 40; i++) {
					ticket.sale();
				}
			}
		}, "cc").start();*/
    }
}
